package com.guigu.tms.dispatch.config;

import com.guigu.tms.commons.dispatch.entity.ScheduleJob;
import com.guigu.tms.dispatch.mapper.ScheduleJobMapper;
import com.guigu.tms.dispatch.utils.ScheduleUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DispatchCommandLineRunner implements CommandLineRunner {

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private ScheduleJobMapper scheduleJobMapper;
    @Override
    public void run(String... args) {
        //查询定时任务
        List<ScheduleJob> scheduleJobList = scheduleJobMapper.selectList(null);
        System.out.println(scheduleJobList);
        for (ScheduleJob scheduleJob : scheduleJobList) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId());
            //如果不存在，则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
    }

}
